﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json.Linq;
using System.Linq;
using System.Text;

namespace CommonUtils
{
    public static class WebUtil
    {
        static WebUtil()
        {
            DbSqlite.Default.VerifyTable<WebHit>();
            DbSqlite.Default.VerifyTable<WebMessage>();
        }

        public static void AddHit(HttpRequest request)
        => DbSqlite.Default.Insert(new WebHit(request));

        public static WebHit[] GetHits()
        => DbSqlite.Default.GetAllEntities<WebHit>();

        public static JObject GetHitInfo(string path = null)
        {
            var hits = GetHits();
            var info = new JObject();
            info.Add("历史点击量", hits.Length);
            info.Add("历史去重点击量", hits.DistinctByProperty(m => m.Host).Count());
            var todayHits = hits.Where(m => m.Time.Date == TimeUtil.Now.Date).ToArray();
            info.Add("今日点击量", todayHits.Length);
            info.Add("今日去重点击量", todayHits.DistinctByProperty(m => m.Host).Count());
            if (!string.IsNullOrEmpty(path))
            {
                info.Add("历史使用量", hits.Where(m => m.Path == path).Count());
                info.Add("历史去重使用量", hits.Where(m => m.Path == path).DistinctByProperty(m => m.Host).Count());
                var todayUsings = hits.Where(m => m.Path == path).Where(m => m.Time.Date == TimeUtil.Now.Date).ToArray();
                info.Add("今日使用量", todayUsings.Count());
                info.Add("今日去重使用量", todayUsings.DistinctByProperty(m => m.Host).Count());
            }
            return info;
        }

        public static void AddMessage(HttpRequest request, string content)
        => DbSqlite.Default.Insert(new WebMessage(request, content));

        public static void DeleteMessage(string id)
        => DbSqlite.Default.Delete<WebMessage>("id", id);

        public static WebMessage[] GetMessages()
        => DbSqlite.Default.GetAllEntities<WebMessage>();

        public static string GetMessageInfo()
        {
            var html = new StringBuilder();
            var messages = GetMessages().OrderByDescending(m => m.Time).Take(10).ToArray();
            var index = messages.Length;
            foreach (var message in messages)
                html.Append("{4}楼[{0}][{1}]<input type='hidden' value='{3}' />：<br />\r\n<pre>{2}</pre><br />\r\n", message.Time, message.HiddenHost, message.Content.DisableHtml(), message.Id, index--);
            return html.ToString();
        }
    }
}
